﻿using System;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using Chess.Common;
using Chess.Server.Model;
using Chess.Server.ViewModel;
using MvvmToolkit.ViewModels;

namespace Chess.Server.ViewModel
{
    public class MainWindowViewModel : ViewModelBase
    {
        public ObservableCollection<ClientViewModel> Clients { get; set; }

        private ServerService _serverService;
        private Dispatcher _dispatcher;

        public MainWindowViewModel(Dispatcher dispatcher)
        {
            Clients = new ObservableCollection<ClientViewModel>();
            //Clients.Add(new ClientViewModel(new ClientModel{Id = 1,IpAddress = "192.168.1.1", Name = "alex", Port = 8080}));
            _dispatcher = dispatcher;
            _serverService = new ServerService(5000);
            _serverService.Update += OnUpdate;
            _serverService.Start();
        }

        private void OnUpdate(PackageType packageType, params object[] args)
        {
            try
            {
                switch (packageType)
                {
                    case PackageType.Exit:
                    case PackageType.LoginRequest:
                    case PackageType.LogoutRequest:
                        {
                            _dispatcher.InvokeAsync(RefillClients);
                        }
                        break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private void RefillClients()
        {
            Clients.Clear();
            foreach (var networkClient in _serverService.Clients)
            {
                var model = new ClientModel();
                model.IpAddress = networkClient.RemoteEp.Address.ToString();
                model.Port = networkClient.RemoteEp.Port;
                model.Name = networkClient.ClientName;
                model.Loggined = networkClient.Loggined;
                Clients.Add(new ClientViewModel(model));
            }
        }
    }
}
